<?php

	// +----------------------------------------------------------------------
	// | 图片模型
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\model\file;

	use app\model\ucenter\User;
	use think\facade\Env;
	use think\facade\Event;

	class Image extends Common
	{

		public static $driver_lists = ['local' => '本地', 'qiniu' => '七牛'];


		/**
		 * 写入修改
		 * @param $data
		 */
		public static function onBeforeInsert($data)
		{
			$data['status'] = 1;
			$data['type'] = isset($data['type']) ? $data['type'] : 'normal';
			$data['url'] = '/' . str_replace(DIRECTORY_SEPARATOR, '/', str_replace(app()->getRootPath() . 'public' . DIRECTORY_SEPARATOR, '', $data['path']));
			// 注册图片修改url事件
			$re = Event::trigger('upload_image_set_url', $data, true);
			if ($re) {
				$data['url'] = $re;
			}
		}

		public function getUrlAttr($value, $data): string
		{
			return $this->_formatUrl($data, 1280);
		}

		/**
		 * 处理好的图片
		 * @param $value
		 * @param $data
		 * @return string
		 * @author  : 微尘 <yicmf@qq.com>
		 * @datetime: 2019/1/29 16:08
		 */
		public function getUrlMiniAttr($value, $data)
		{
			return $this->_formatUrl($data, 60);
		}

		/**
		 * 处理好的图片
		 * @param $value
		 * @param $data
		 * @return string
		 * @author  : 微尘 <yicmf@qq.com>
		 * @datetime: 2019/1/29 16:08
		 */
		public function getUrlSmallAttr($value, $data)
		{
			return $this->_formatUrl($data, 240);
		}

		/**
		 * 处理好的图片
		 * @param $value
		 * @param $data
		 * @return string
		 * @author  : 微尘 <yicmf@qq.com>
		 * @datetime: 2019/1/29 16:08
		 */
		public function getUrlNormalAttr($value, $data)
		{
			return $this->_formatUrl($data, 360);
		}

		/**
		 * 处理好的图片
		 * @param $value
		 * @param $data
		 * @return string
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public function getUrlBigAttr($value, $data): string
		{
			return $this->_formatUrl($data, 1280);
		}

		protected function _formatUrl($data, $width): string
		{
			if ('qiniu' == $data['driver'] && 'qiniu' == config('upload_driver.driver')) {
				$domain = config('upload_driver.qiniu_domain');
			} else {
				if ('cli' != PHP_SAPI) {
					$domain = self::$request->domain();
					if (!$domain)
					{
						$domain = config('setting.host');
					}
				} else {
					$domain = config('setting.host');
				}

			}
			return $domain . $data['url'];
		}

        public function getOriginalAttr($value, $data)
        {
            return $data['url'];
        }
		// 定义关联方法
		public function user()
		{
			return $this->belongsTo(User::class);
		}

		public function album()
		{
			return $this->belongsTo(GiftCard::class);
		}

		// 以下是自动完成

		protected $type = [
			'info' => 'array',
		];


	}
